package cn.milai.amtc.step5;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.milai.amtc.Audio;

/**
 * 使用单独的线程池分时播放所有音频 -> 基本解决问题，但无法灵活地暂停/停止一个音频的播放
 */
public class AudioManager {

	private static final int THREAD_NUM = 3;
	private static final int PER_FRAMES = 16;
	private static final ExecutorService threadPool;

	private static Queue<Audio> audios = new ConcurrentLinkedQueue<Audio>();

	static {
		threadPool = Executors.newFixedThreadPool(THREAD_NUM);
		new Thread() {
			public void run() {
				while (true) {
					{
						for (Audio a : audios) {
							if (a.isComplete()) {
								audios.remove(a);
							} else {
								audios.remove(a);
								threadPool.execute(() -> {
									a.play(PER_FRAMES);
									audios.add(a);
								});
							}
						}
					}
				}
			};
		}.start();
	}

	public static void add(Audio audio) {
		audios.add(audio);
	}

	public static void play() {
	}
}
